package com.offcn.sellergoods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.offcn.order.entity.Cart;
import com.offcn.order.pojo.OrderItem;
import com.offcn.sellergoods.dao.ItemMapper;
import com.offcn.sellergoods.pojo.Item;
import com.offcn.sellergoods.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired(required = false)
    private ItemMapper itemMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<Item> findAll() {
        List<Item> itemList = itemMapper.selectList(new QueryWrapper<Item>());
        return itemList;
    }

    @Override
    public Item findItemById(Long id) {
        Item item = itemMapper.selectById(id);
        return item;
    }

    @Override
    public void decrNum(String username) {
        String cartListStr = (String) stringRedisTemplate.boundHashOps("cartList").get(username);
        List<Cart> cartList = JSON.parseArray(cartListStr, Cart.class);
        for (Cart cart : cartList) {
            for (OrderItem orderItem : cart.getOrderItemList()) {
                int rows = itemMapper.decrNum(orderItem);
                if (rows == 0){
                    throw new RuntimeException("库存不足，修改库存失败");
                }
            }
        }
    }
}
